<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="year">
        <el-input
          v-model="queryParams.year"
          placeholder="请输入日期"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['teaching:holidayConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teaching:holidayConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teaching:holidayConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['teaching:holidayConfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="holidayConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="日期" align="center" prop="year" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['teaching:holidayConfig:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['teaching:holidayConfig:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改节假日配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="holidayConfigRef" :model="form" :rules="rules" label-width="100px">
        <!-- 动态渲染每个节日 -->
        <template v-for="(holiday, index) in holidays" :key="index">
          <el-row :gutter="20">
            <el-col :span="3">
              <div class="label">{{ holiday.name }}</div>
            </el-col>
            <el-col :span="11">
              <el-form-item :label="`起始日期`">
                <el-date-picker
                  v-model="holiday.startDate"
                  type="date"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`持续几天`">
                <el-input
                  v-model.number="holiday.days"
                  placeholder="持续几天"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="HolidayConfig">
import { listHolidayConfig, getHolidayConfig, delHolidayConfig, addHolidayConfig, updateHolidayConfig } from "@/api/teaching/holidayConfig"
import log from "../../monitor/job/log.vue";

const { proxy } = getCurrentInstance()

const holidayConfigList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 模拟节日数据（可从后端获取）
const holidays = ref([
  { name: '元旦节' },
  { name: '春节' },
  { name: '清明节' },
  { name: '劳动节'},
  { name: '端午节'},
  { name: '中秋节'},
  { name: '国庆节'}
])

const data = reactive({
  form: {
    content:[]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: null,
  },
  rules: {
    year: [
      { required: true, message: "日期不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "内容不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询节假日配置列表 */
function getList() {
  loading.value = true
  listHolidayConfig(queryParams.value).then(response => {
    holidayConfigList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = holidays.value.reduce((acc, holiday) => {
    acc[holiday.key] = {
      startDate: '',
      days: ''
    }
    return acc
  }, {})
  holidays.value = [
    { name: '元旦节' },
    { name: '春节' },
    { name: '清明节' },
    { name: '劳动节'},
    { name: '端午节'},
    { name: '中秋节'},
    { name: '国庆节'}
  ]
  proxy.resetForm("holidayConfigRef")
}

function initRules() {
  rules.value = holidays.value.reduce((acc, holiday) => {
    acc[`${holiday.key}.startDate`] = [
      { required: true, message: `${holiday.name}起始日期不能为空`, trigger: "change" }
    ]
    acc[`${holiday.key}.days`] = [
      { required: true, message: `${holiday.name}持续天数不能为空`, trigger: "blur" }
    ]
    return acc
  }, {})
}
initRules()

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加节假日配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getHolidayConfig(_id).then(response => {

    holidays.value = JSON.parse(response.data.content)

    form.value = response.data
    console.log(form.value)
    open.value = true
    title.value = "修改节假日配置"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["holidayConfigRef"].validate(valid => {
    if (valid) {
      form.value = {
        id: form.value.id,
        content : JSON.stringify(holidays.value)
      }
      console.log(form.value)
      if (form.value.id != null) {
        updateHolidayConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 添加
        addHolidayConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除节假日配置编号为"' + _ids + '"的数据项？').then(function() {
    return delHolidayConfig(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('teaching/holidayConfig/export', {
    ...queryParams.value
  }, `holidayConfig_${new Date().getTime()}.xlsx`)
}


getList()
</script>
